using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

namespace EditorTools
{
    public class PrefabDocGenerator : EditorWindow
    {
        private string prefabPath = "";
        private string outputDirectory = "PrefabDocs";
        private DefaultAsset selectedFolder;
        private List<UnityEngine.Object> selectedPrefabs = new List<UnityEngine.Object>();
        
        [SerializeField]
        private List<string> commentKeys = new List<string>();
        [SerializeField]
        private List<string> commentValues = new List<string>();
        
        // 使用属性访问序列化后的注释列表
        private Dictionary<string, string> nodeComments
        {
            get
            {
                var result = new Dictionary<string, string>();
                for (int i = 0; i < commentKeys.Count && i < commentValues.Count; i++)
                {
                    result[commentKeys[i]] = commentValues[i];
                }
                return result;
            }
        }
        
        private Vector2 commentsScrollPosition;
        private Vector2 prefabsScrollPosition;
        private Vector2 nodeLimitsScrollPosition; // 节点限制滚动位置
        private bool processAllPrefabsInFolder = false;
        private bool showCommentEditor = false;
        private bool showNodeLimitEditor = false; // 是否显示节点限制编辑器
        private string commentNodeName = "";
        private string commentText = "";
        private string limitNodeName = ""; // 节点名称输入
        private string limitLevelText = ""; // 层级限制输入
        private bool generateWithComments = true;
        private bool generateSpecialPrefixDocs = true;
        private readonly string[] specialPrefixes = new string[] { "M_", "P_", "C_" };
        private Dictionary<string, int> nodeLevelLimits = new Dictionary<string, int>
        {
            { "C_CannonInfo_Container", 1 } // 限制C_CannonInfo_Container只生成1层
        };
        private GUIStyle headerStyle;
        
        // 新增：导出格式选项
        private enum OutputFormat
        {
            TreeFormat,    // 树形格式（原格式）
            CompactFormat, // 简洁缩进格式
            CollapsibleFormat // 可折叠格式
        }
        private OutputFormat selectedFormat = OutputFormat.TreeFormat;

        // 使用布尔字段替代枚举，支持多选格式
        private bool useTreeFormat = false;
        private bool useCompactFormat = false;
        private bool useCollapsibleFormat = true; // 默认选择可折叠格式

        // 添加到Tools菜单
        [MenuItem("Tools/ForAI/生成预制件节点文档", false, 100)]
        public static void ShowWindow()
        {
            GetWindow<PrefabDocGenerator>("预制件文档生成工具");
        }

        private void OnEnable()
        {
            // 创建自定义样式
            headerStyle = new GUIStyle();
            headerStyle.fontSize = 14;
            headerStyle.fontStyle = FontStyle.Bold;
            headerStyle.margin = new RectOffset(5, 5, 10, 10);
            
            // 尝试从EditorPrefs加载注释数据
            LoadCommentsFromPrefs();
            
            // 加载上次选择的输出目录
            if (EditorPrefs.HasKey("PrefabDocGenerator_OutputDirectory"))
            {
                outputDirectory = EditorPrefs.GetString("PrefabDocGenerator_OutputDirectory");
            }

            // 加载上次选择的文件夹
            if (EditorPrefs.HasKey("PrefabDocGenerator_SelectedFolder"))
            {
                string folderPath = EditorPrefs.GetString("PrefabDocGenerator_SelectedFolder");
                if (!string.IsNullOrEmpty(folderPath) && Directory.Exists(folderPath))
                {
                    selectedFolder = AssetDatabase.LoadAssetAtPath<DefaultAsset>(folderPath);
                }
            }
            
            // 加载上次选择的处理模式
            if (EditorPrefs.HasKey("PrefabDocGenerator_ProcessMode"))
            {
                int mode = EditorPrefs.GetInt("PrefabDocGenerator_ProcessMode", 0);
                processAllPrefabsInFolder = mode == 1;
                showCommentEditor = mode == 2;
            }
            
            // 加载上次是否包含注释的选择
            if (EditorPrefs.HasKey("PrefabDocGenerator_GenerateWithComments"))
            {
                generateWithComments = EditorPrefs.GetBool("PrefabDocGenerator_GenerateWithComments", true);
            }
            
            // 加载是否生成特殊前缀节点文档的选择
            if (EditorPrefs.HasKey("PrefabDocGenerator_GenerateSpecialPrefixDocs"))
            {
                generateSpecialPrefixDocs = EditorPrefs.GetBool("PrefabDocGenerator_GenerateSpecialPrefixDocs", true);
            }
            
            // 加载多选格式设置
            if (EditorPrefs.HasKey("PrefabDocGenerator_UseTreeFormat"))
            {
                useTreeFormat = EditorPrefs.GetBool("PrefabDocGenerator_UseTreeFormat", false);
            }
            if (EditorPrefs.HasKey("PrefabDocGenerator_UseCompactFormat"))
            {
                useCompactFormat = EditorPrefs.GetBool("PrefabDocGenerator_UseCompactFormat", false);
            }
            if (EditorPrefs.HasKey("PrefabDocGenerator_UseCollapsibleFormat"))
            {
                useCollapsibleFormat = EditorPrefs.GetBool("PrefabDocGenerator_UseCollapsibleFormat", true);
            }
            
            // 加载节点层级限制
            LoadNodeLimitsFromPrefs();
        }
        
        private void OnDisable()
        {
            // 在编辑器窗口关闭时保存设置
            SaveCommentsToPrefs();
            SaveNodeLimitsToPrefs();
            SaveOutputDirectoryToPrefs();
            SaveSelectedFolderToPrefs();
            SaveProcessModeToPrefs();
            SaveGenerateWithCommentsToPrefs();
            SaveFormatSettingsToPrefs();
        }
        
        // 保存格式设置到EditorPrefs
        private void SaveFormatSettingsToPrefs()
        {
            EditorPrefs.SetBool("PrefabDocGenerator_UseTreeFormat", useTreeFormat);
            EditorPrefs.SetBool("PrefabDocGenerator_UseCompactFormat", useCompactFormat);
            EditorPrefs.SetBool("PrefabDocGenerator_UseCollapsibleFormat", useCollapsibleFormat);
        }
        
        // 保存注释到EditorPrefs
        private void SaveCommentsToPrefs()
        {
            // 将注释转换为JSON并保存
            string json = EditorJsonUtility.ToJson(this);
            EditorPrefs.SetString("PrefabDocGenerator_Comments", json);
        }
        
        // 从EditorPrefs加载注释
        private void LoadCommentsFromPrefs()
        {
            if (EditorPrefs.HasKey("PrefabDocGenerator_Comments"))
            {
                string json = EditorPrefs.GetString("PrefabDocGenerator_Comments");
                EditorJsonUtility.FromJsonOverwrite(json, this);
            }
        }

        // 保存输出目录到EditorPrefs
        private void SaveOutputDirectoryToPrefs()
        {
            EditorPrefs.SetString("PrefabDocGenerator_OutputDirectory", outputDirectory);
        }
        
        // 保存选择的文件夹到EditorPrefs
        private void SaveSelectedFolderToPrefs()
        {
            if (selectedFolder != null)
            {
                string folderPath = AssetDatabase.GetAssetPath(selectedFolder);
                EditorPrefs.SetString("PrefabDocGenerator_SelectedFolder", folderPath);
            }
        }
        
        // 保存处理模式到EditorPrefs
        private void SaveProcessModeToPrefs()
        {
            int mode = showCommentEditor ? 2 : (processAllPrefabsInFolder ? 1 : 0);
            EditorPrefs.SetInt("PrefabDocGenerator_ProcessMode", mode);
        }
        
        // 保存是否包含注释的选择
        private void SaveGenerateWithCommentsToPrefs()
        {
            EditorPrefs.SetBool("PrefabDocGenerator_GenerateWithComments", generateWithComments);
            EditorPrefs.SetBool("PrefabDocGenerator_GenerateSpecialPrefixDocs", generateSpecialPrefixDocs);
        }

        // 保存节点层级限制到EditorPrefs
        private void SaveNodeLimitsToPrefs()
        {
            try
            {
                string json = JsonUtility.ToJson(new NodeLimitsWrapper(nodeLevelLimits));
                EditorPrefs.SetString("PrefabDocGenerator_NodeLimits", json);
            }
            catch (Exception ex)
            {
                Debug.LogError($"保存节点层级限制时出错: {ex.Message}");
            }
        }

        // 从EditorPrefs加载节点层级限制
        private void LoadNodeLimitsFromPrefs()
        {
            try
            {
                if (EditorPrefs.HasKey("PrefabDocGenerator_NodeLimits"))
                {
                    string json = EditorPrefs.GetString("PrefabDocGenerator_NodeLimits");
                    NodeLimitsWrapper wrapper = JsonUtility.FromJson<NodeLimitsWrapper>(json);
                    if (wrapper != null && wrapper.nodeLimitPairs != null)
                    {
                        nodeLevelLimits = new Dictionary<string, int>();
                        foreach (var pair in wrapper.nodeLimitPairs)
                        {
                            if (!string.IsNullOrEmpty(pair.nodeName))
                            {
                                nodeLevelLimits[pair.nodeName] = pair.level;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"加载节点层级限制时出错: {ex.Message}");
                // 确保有默认值
                if (nodeLevelLimits == null || nodeLevelLimits.Count == 0)
                {
                    nodeLevelLimits = new Dictionary<string, int>
                    {
                        { "C_CannonInfo_Container", 1 }
                    };
                }
            }
        }

        private void OnGUI()
        {
            EditorGUILayout.LabelField("预制件节点文档生成工具", headerStyle);
            EditorGUILayout.Space(10);

            // 输出目录设置
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("输出目录:", GUILayout.Width(60));
            string newOutputDirectory = EditorGUILayout.TextField(outputDirectory);
            if (newOutputDirectory != outputDirectory)
            {
                outputDirectory = newOutputDirectory;
                SaveOutputDirectoryToPrefs();
            }
            
            if (GUILayout.Button("浏览", GUILayout.Width(60)))
            {
                string path = EditorUtility.OpenFolderPanel("选择输出目录", outputDirectory, "");
                if (!string.IsNullOrEmpty(path))
                {
                    outputDirectory = path;
                    SaveOutputDirectoryToPrefs();
                    GUI.FocusControl(null); // 清除焦点，确保UI更新
                    Repaint(); // 强制重绘窗口
                    Debug.Log($"已设置输出目录: {outputDirectory}");
                }
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Space(10);

            // 添加选项卡
            string[] tabs = { "单个预制件", "文件夹批处理", "节点注释", "层级限制" };
            int selectedTab = showNodeLimitEditor ? 3 : (showCommentEditor ? 2 : (processAllPrefabsInFolder ? 1 : 0));
            
            int newSelectedTab = GUILayout.Toolbar(selectedTab, tabs);

            bool modeChanged = false;
            
            if (newSelectedTab != selectedTab)
            {
                modeChanged = true;
                showNodeLimitEditor = (newSelectedTab == 3);
                showCommentEditor = (newSelectedTab == 2);
                processAllPrefabsInFolder = (newSelectedTab == 1);
            }
            
            if (modeChanged)
            {
                SaveProcessModeToPrefs();
            }
            
            EditorGUILayout.Space(10);
            
            // 根据当前选择的选项卡显示对应的UI
            if (showNodeLimitEditor)
            {
                DrawNodeLimitEditorMode();
            }
            else if (showCommentEditor)
            {
                DrawCommentEditorMode();
            }
            else if (processAllPrefabsInFolder)
            {
                DrawBatchPrefabMode();
            }
            else
            {
                DrawSinglePrefabMode();
            }

            EditorGUILayout.Space(10);

            // 输出格式选择
            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("输出格式选择:", EditorStyles.boldLabel);

            EditorGUILayout.BeginVertical(EditorStyles.helpBox);

            bool prevTreeFormat = useTreeFormat;
            bool prevCompactFormat = useCompactFormat;
            bool prevCollapsibleFormat = useCollapsibleFormat;

            useTreeFormat = EditorGUILayout.ToggleLeft("树形格式 (Tree Format)", useTreeFormat);
            useCompactFormat = EditorGUILayout.ToggleLeft("简洁缩进格式 (Compact Format)", useCompactFormat);
            useCollapsibleFormat = EditorGUILayout.ToggleLeft("可折叠格式 (Collapsible Format) - MD格式", useCollapsibleFormat);

            // 确保至少选择一种格式
            if (!useTreeFormat && !useCompactFormat && !useCollapsibleFormat)
            {
                useCollapsibleFormat = true; // 默认选择可折叠格式
            }

            // 如果有变化，保存设置
            if (prevTreeFormat != useTreeFormat || 
                prevCompactFormat != useCompactFormat || 
                prevCollapsibleFormat != useCollapsibleFormat)
            {
                SaveFormatSettingsToPrefs();
            }

            EditorGUILayout.EndVertical();

            bool prevGenerateWithComments = generateWithComments;
            generateWithComments = EditorGUILayout.Toggle("包含节点注释", generateWithComments);
            
            if (prevGenerateWithComments != generateWithComments)
            {
                SaveGenerateWithCommentsToPrefs();
            }
            
            EditorGUILayout.Space(10);
            
            // 添加特殊前缀节点文档生成选项
            bool newGenerateSpecialPrefixDocs = EditorGUILayout.ToggleLeft("为特殊前缀节点(M_、P_、C_)生成单独文档", generateSpecialPrefixDocs);
            if (newGenerateSpecialPrefixDocs != generateSpecialPrefixDocs)
            {
                generateSpecialPrefixDocs = newGenerateSpecialPrefixDocs;
                SaveGenerateWithCommentsToPrefs();
            }
            
            EditorGUILayout.Space(10);
            
            if (GUILayout.Button("生成文档", GUILayout.Height(30)))
            {
                // 根据选择的模式生成文档
                if (showCommentEditor)
                {
                    EditorUtility.DisplayDialog("提示", "请先切换到单个预制件或文件夹批处理模式", "确定");
                }
                else if (processAllPrefabsInFolder)
                {
                    if (selectedFolder != null)
                    {
                        string folderPath = AssetDatabase.GetAssetPath(selectedFolder);
                        if (!string.IsNullOrEmpty(folderPath) && System.IO.Directory.Exists(folderPath))
                        {
                            GenerateDocsForFolder(folderPath);
                        }
                        else
                        {
                            EditorUtility.DisplayDialog("错误", "请选择有效的文件夹", "确定");
                        }
                    }
                    else
                    {
                        EditorUtility.DisplayDialog("错误", "请先选择文件夹", "确定");
                    }
                }
                else
                {
                    if (selectedPrefabs.Count > 0)
                    {
                        bool allValid = true;
                        foreach (var prefab in selectedPrefabs)
                        {
                            if (prefab == null)
                            {
                                allValid = false;
                                break;
                            }
                        }
                        
                        if (allValid)
                        {
                            GenerateDocsForSelectedPrefabs();
                        }
                        else
                        {
                            EditorUtility.DisplayDialog("错误", "请选择有效的预制件", "确定");
                        }
                    }
                    else
                    {
                        EditorUtility.DisplayDialog("错误", "请先选择预制件", "确定");
                    }
                }
            }
        }

        private void DrawSinglePrefabMode()
        {
            EditorGUILayout.LabelField("选择一个或多个预制件:", EditorStyles.boldLabel);

            // 预制件列表
            prefabsScrollPosition = EditorGUILayout.BeginScrollView(prefabsScrollPosition, GUILayout.Height(200));
            for (int i = 0; i < selectedPrefabs.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();
                UnityEngine.Object newPrefab = EditorGUILayout.ObjectField(selectedPrefabs[i], typeof(UnityEngine.Object), false);
                if (newPrefab != selectedPrefabs[i])
                {
                    selectedPrefabs[i] = newPrefab;
                }
                
                if (GUILayout.Button("X", GUILayout.Width(25)))
                {
                    selectedPrefabs.RemoveAt(i);
                    GUIUtility.ExitGUI();
                }
                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.EndScrollView();

            // 处理拖放操作
            Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
            
            // 创建自定义样式
            GUIStyle dropBoxStyle = new GUIStyle(EditorStyles.helpBox);
            dropBoxStyle.alignment = TextAnchor.MiddleCenter;
            dropBoxStyle.fontStyle = FontStyle.Bold;
            
            // 绘制拖拽区域
            Color originalColor = GUI.color;
            GUI.color = new Color(0.8f, 0.8f, 1.0f, 0.8f);
            GUI.Box(dropArea, "拖拽预制件到这里", dropBoxStyle);
            
            // 检测是否有拖拽操作
            Event evt = Event.current;
            switch (evt.type)
            {
                case EventType.DragUpdated:
                case EventType.DragPerform:
                    if (!dropArea.Contains(evt.mousePosition))
                        break;
                        
                    // 改变鼠标指针为可接受状态
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    
                    // 高亮拖拽区域
                    if (evt.type == EventType.DragUpdated)
                    {
                        GUI.color = new Color(0.7f, 0.9f, 1.0f, 0.9f);
                        GUI.Box(dropArea, "释放鼠标添加预制件", dropBoxStyle);
                        Repaint();
                    }
                    
                    if (evt.type == EventType.DragPerform)
                    {
                        DragAndDrop.AcceptDrag();
                        
                        foreach (UnityEngine.Object draggedObject in DragAndDrop.objectReferences)
                        {
                            // 检查是否为预制件
                            string path = AssetDatabase.GetAssetPath(draggedObject);
                            if (path.EndsWith(".prefab"))
                            {
                                GameObject prefabObject = draggedObject as GameObject;
                                if (prefabObject != null && PrefabUtility.GetPrefabAssetType(draggedObject) != PrefabAssetType.NotAPrefab)
                                {
                                    if (!selectedPrefabs.Contains(draggedObject))
                                    {
                                        selectedPrefabs.Add(draggedObject);
                                    }
                                }
                            }
                        }
                    }
                    
                    evt.Use();
                    break;
            }
            
            // 恢复原始颜色
            GUI.color = originalColor;

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("添加预制件"))
            {
                string path = EditorUtility.OpenFilePanel("选择预制件", Application.dataPath, "prefab");
                if (!string.IsNullOrEmpty(path))
                {
                    // 转换为Assets相对路径
                    string relativePath = "Assets" + path.Substring(Application.dataPath.Length);
                    UnityEngine.Object prefabAsset = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(relativePath);
                    if (prefabAsset != null)
                    {
                        selectedPrefabs.Add(prefabAsset);
                    }
                    else
                    {
                        // 尝试不同的加载方法
                        GameObject goPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(relativePath);
                        if (goPrefab != null)
                        {
                            selectedPrefabs.Add(goPrefab);
                        }
                        else
                        {
                            EditorUtility.DisplayDialog("错误", $"无法加载预制件: {relativePath}", "确定");
                        }
                    }
                }
            }
            if (GUILayout.Button("清空列表"))
            {
                selectedPrefabs.Clear();
            }
            EditorGUILayout.EndHorizontal();
        }

        private void DrawBatchPrefabMode()
        {
            EditorGUILayout.LabelField("选择预制件所在文件夹:", EditorStyles.boldLabel);
            
            // 显示当前选择的文件夹路径
            if (selectedFolder != null)
            {
                string folderPath = AssetDatabase.GetAssetPath(selectedFolder);
                EditorGUILayout.LabelField("当前选择:", folderPath);
            }
            
            EditorGUILayout.BeginHorizontal();
            UnityEngine.Object newFolder = EditorGUILayout.ObjectField("文件夹", selectedFolder, typeof(DefaultAsset), false);
            if (newFolder != selectedFolder)
            {
                // 检查是否为文件夹
                string path = AssetDatabase.GetAssetPath(newFolder);
                if (!string.IsNullOrEmpty(path) && System.IO.Directory.Exists(path))
                {
                    selectedFolder = newFolder as DefaultAsset;
                    SaveSelectedFolderToPrefs();
                }
                else if (newFolder != null)
                {
                    EditorUtility.DisplayDialog("错误", "请选择一个有效的文件夹", "确定");
                }
            }
            
            if (GUILayout.Button("浏览", GUILayout.Width(60)))
            {
                string path = EditorUtility.OpenFolderPanel("选择预制件文件夹", Application.dataPath, "");
                if (!string.IsNullOrEmpty(path))
                {
                    string relativePath = "Assets" + path.Substring(Application.dataPath.Length);
                    selectedFolder = AssetDatabase.LoadAssetAtPath<DefaultAsset>(relativePath);
                    SaveSelectedFolderToPrefs();
                }
            }
            EditorGUILayout.EndHorizontal();
            
            // 添加拖放区域用于文件夹拖放
            Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
            
            // 创建自定义样式
            GUIStyle dropBoxStyle = new GUIStyle(EditorStyles.helpBox);
            dropBoxStyle.alignment = TextAnchor.MiddleCenter;
            dropBoxStyle.fontStyle = FontStyle.Bold;
            
            // 绘制拖拽区域
            Color originalColor = GUI.color;
            GUI.color = new Color(0.8f, 1.0f, 0.8f, 0.8f);
            GUI.Box(dropArea, "拖拽文件夹到这里", dropBoxStyle);
            
            // 检测是否有拖拽操作
            Event evt = Event.current;
            switch (evt.type)
            {
                case EventType.DragUpdated:
                case EventType.DragPerform:
                    if (!dropArea.Contains(evt.mousePosition))
                        break;
                        
                    // 改变鼠标指针为可接受状态
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    
                    // 高亮拖拽区域
                    if (evt.type == EventType.DragUpdated)
                    {
                        GUI.color = new Color(0.7f, 1.0f, 0.7f, 0.9f);
                        GUI.Box(dropArea, "释放鼠标选择文件夹", dropBoxStyle);
                        Repaint();
                    }
                    
                    if (evt.type == EventType.DragPerform)
                    {
                        DragAndDrop.AcceptDrag();
                        
                        foreach (UnityEngine.Object draggedObject in DragAndDrop.objectReferences)
                        {
                            // 检查是否为文件夹
                            string path = AssetDatabase.GetAssetPath(draggedObject);
                            if (!string.IsNullOrEmpty(path) && System.IO.Directory.Exists(path))
                            {
                                DefaultAsset folderAsset = draggedObject as DefaultAsset;
                                if (folderAsset != null)
                                {
                                    selectedFolder = folderAsset;
                                    SaveSelectedFolderToPrefs();
                                    break; // 只使用第一个拖拽的文件夹
                                }
                            }
                        }
                    }
                    
                    evt.Use();
                    break;
            }
            
            // 恢复原始颜色
            GUI.color = originalColor;
            
            EditorGUILayout.Space(5);
            EditorGUILayout.HelpBox("将处理选定文件夹中的所有预制件", MessageType.Info);
            
            // 显示统计信息
            if (selectedFolder != null)
            {
                string folderPath = AssetDatabase.GetAssetPath(selectedFolder);
                if (!string.IsNullOrEmpty(folderPath) && System.IO.Directory.Exists(folderPath))
                {
                    try {
                        string[] prefabFiles = System.IO.Directory.GetFiles(folderPath, "*.prefab", System.IO.SearchOption.AllDirectories);
                        EditorGUILayout.LabelField($"共找到 {prefabFiles.Length} 个预制件文件");
                    } 
                    catch (Exception ex) 
                    {
                        Debug.LogWarning($"获取预制件数量时出错: {ex.Message}");
                    }
                }
            }
        }

        private void DrawCommentEditorMode()
        {
            EditorGUILayout.LabelField("节点注释编辑:", EditorStyles.boldLabel);

            // 添加新注释
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("节点名称:", GUILayout.Width(60));
            commentNodeName = EditorGUILayout.TextField(commentNodeName);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("注释:", GUILayout.Width(60));
            commentText = EditorGUILayout.TextField(commentText);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("添加/更新注释") && !string.IsNullOrEmpty(commentNodeName))
            {
                // 检查是否已存在该节点名
                int existingIndex = commentKeys.IndexOf(commentNodeName);
                if (existingIndex >= 0)
                {
                    // 更新现有注释
                    commentValues[existingIndex] = commentText;
                }
                else
                {
                    // 添加新注释
                    commentKeys.Add(commentNodeName);
                    commentValues.Add(commentText);
                }
                
                commentNodeName = "";
                commentText = "";
                
                // 保存注释到EditorPrefs
                SaveCommentsToPrefs();
                
                // 强制重绘窗口
                Repaint();
            }
            EditorGUILayout.EndHorizontal();

            // 显示已有注释
            EditorGUILayout.Space(10);
            EditorGUILayout.LabelField("已添加注释:", EditorStyles.boldLabel);
            
            if (commentKeys.Count == 0)
            {
                EditorGUILayout.HelpBox("尚未添加任何节点注释", MessageType.Info);
            }
            else
            {
                commentsScrollPosition = EditorGUILayout.BeginScrollView(commentsScrollPosition, GUILayout.Height(200));
                List<int> indicesToRemove = new List<int>();
                
                var comments = nodeComments;
                for (int i = 0; i < commentKeys.Count; i++)
                {
                    if (i >= commentValues.Count) continue;
                    
                    string key = commentKeys[i];
                    string value = commentValues[i];
                    
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField(key, GUILayout.Width(150));
                    EditorGUILayout.LabelField(value);
                    if (GUILayout.Button("编辑", GUILayout.Width(40)))
                    {
                        // 点击编辑按钮时,填充编辑框
                        commentNodeName = key;
                        commentText = value;
                    }
                    if (GUILayout.Button("X", GUILayout.Width(25)))
                    {
                        indicesToRemove.Add(i);
                    }
                    EditorGUILayout.EndHorizontal();
                }
                
                // 从后向前删除，避免索引变化
                indicesToRemove.Sort((a, b) => b.CompareTo(a));
                foreach (var index in indicesToRemove)
                {
                    commentKeys.RemoveAt(index);
                    if (index < commentValues.Count)
                    {
                        commentValues.RemoveAt(index);
                    }
                }
                
                if (indicesToRemove.Count > 0)
                {
                    // 保存注释到EditorPrefs
                    SaveCommentsToPrefs();
                }
                
                EditorGUILayout.EndScrollView();
            }

            // 导入/导出注释
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("导入注释"))
            {
                string path = EditorUtility.OpenFilePanel("选择注释文件", "", "json");
                if (!string.IsNullOrEmpty(path))
                {
                    ImportComments(path);
                }
            }
            if (GUILayout.Button("导出注释"))
            {
                string path = EditorUtility.SaveFilePanel("保存注释文件", "", "prefab_comments", "json");
                if (!string.IsNullOrEmpty(path))
                {
                    ExportComments(path);
                }
            }
            if (GUILayout.Button("清空注释"))
            {
                if (EditorUtility.DisplayDialog("确认", "确定要清空所有注释吗？", "确定", "取消"))
                {
                    commentKeys.Clear();
                    commentValues.Clear();
                    SaveCommentsToPrefs();
                }
            }
            EditorGUILayout.EndHorizontal();
        }

        private void DrawNodeLimitEditorMode()
        {
            EditorGUILayout.LabelField("节点层级限制编辑:", EditorStyles.boldLabel);
            EditorGUILayout.HelpBox("在这里可以设置特定节点的层级限制，限制生成特殊节点文档时的层级深度", MessageType.Info);

            // 添加新限制
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("节点名称:", GUILayout.Width(60));
            limitNodeName = EditorGUILayout.TextField(limitNodeName);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("层级限制:", GUILayout.Width(60));
            limitLevelText = EditorGUILayout.TextField(limitLevelText);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("添加/更新限制") && !string.IsNullOrEmpty(limitNodeName))
            {
                int limitLevel;
                if (int.TryParse(limitLevelText, out limitLevel) && limitLevel >= 0)
                {
                    // 更新字典
                    nodeLevelLimits[limitNodeName] = limitLevel;
                    
                    // 保存到EditorPrefs
                    SaveNodeLimitsToPrefs();
                    
                    // 清空输入框
                    limitNodeName = "";
                    limitLevelText = "";
                    
                    // 强制重绘窗口
                    Repaint();
                }
                else
                {
                    EditorUtility.DisplayDialog("错误", "请输入有效的层级限制值（非负整数）", "确定");
                }
            }
            EditorGUILayout.EndHorizontal();

            // 显示已有限制
            EditorGUILayout.Space(10);
            EditorGUILayout.LabelField("已添加层级限制:", EditorStyles.boldLabel);
            
            if (nodeLevelLimits.Count == 0)
            {
                EditorGUILayout.HelpBox("尚未添加任何节点层级限制", MessageType.Info);
            }
            else
            {
                nodeLimitsScrollPosition = EditorGUILayout.BeginScrollView(nodeLimitsScrollPosition, GUILayout.Height(200));
                List<string> keysToRemove = new List<string>();
                
                foreach (var kvp in nodeLevelLimits)
                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField(kvp.Key, GUILayout.Width(250));
                    EditorGUILayout.LabelField(kvp.Value.ToString() + " 层", GUILayout.Width(80));
                    if (GUILayout.Button("编辑", GUILayout.Width(60)))
                    {
                        // 点击编辑按钮时,填充编辑框
                        limitNodeName = kvp.Key;
                        limitLevelText = kvp.Value.ToString();
                    }
                    if (GUILayout.Button("X", GUILayout.Width(25)))
                    {
                        keysToRemove.Add(kvp.Key);
                    }
                    EditorGUILayout.EndHorizontal();
                }
                
                // 从后向前删除，避免索引变化
                foreach (var key in keysToRemove)
                {
                    nodeLevelLimits.Remove(key);
                }
                
                if (keysToRemove.Count > 0)
                {
                    // 保存到EditorPrefs
                    SaveNodeLimitsToPrefs();
                }
                
                EditorGUILayout.EndScrollView();
            }

            // 导入/导出限制
            EditorGUILayout.Space(10);
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("导入限制"))
            {
                string path = EditorUtility.OpenFilePanel("选择层级限制文件", "", "json");
                if (!string.IsNullOrEmpty(path))
                {
                    ImportNodeLimits(path);
                }
            }
            if (GUILayout.Button("导出限制"))
            {
                string path = EditorUtility.SaveFilePanel("保存层级限制文件", "", "node_limits", "json");
                if (!string.IsNullOrEmpty(path))
                {
                    ExportNodeLimits(path);
                }
            }
            if (GUILayout.Button("清空限制"))
            {
                if (EditorUtility.DisplayDialog("确认", "确定要清空所有节点层级限制吗？", "确定", "取消"))
                {
                    nodeLevelLimits.Clear();
                    SaveNodeLimitsToPrefs();
                }
            }
            EditorGUILayout.EndHorizontal();
        }

        private void GenerateDocsForSelectedPrefabs()
        {
            // 确保输出目录是有效路径
            string validOutputDirectory = outputDirectory;
            Debug.Log($"生成文档使用目录: {validOutputDirectory}");
            
            // 移除路径中可能存在的无效字符
            foreach (char invalidChar in Path.GetInvalidPathChars())
            {
                validOutputDirectory = validOutputDirectory.Replace(invalidChar.ToString(), "");
            }
            
            // 如果路径为空，使用默认值
            if (string.IsNullOrWhiteSpace(validOutputDirectory))
            {
                validOutputDirectory = "PrefabDocs";
                Debug.LogWarning("输出目录为空，使用默认目录: PrefabDocs");
            }
            
            // 确保路径不包含非法字符或格式
            // 对于Windows路径，允许第二个字符是冒号（例如C:）
            if (validOutputDirectory.Length >= 2 && validOutputDirectory[1] == ':')
            {
                // Windows路径，允许盘符后的冒号
                string pathWithoutDrive = validOutputDirectory.Substring(2);
                if (pathWithoutDrive.IndexOfAny(new char[] { '<', '>', ':', '"', '|', '?', '*' }) >= 0)
                {
                    Debug.LogWarning($"输出目录包含非法字符: {validOutputDirectory}，使用默认目录: PrefabDocs");
                    validOutputDirectory = "PrefabDocs";
                }
            }
            else if (validOutputDirectory.IndexOfAny(new char[] { '<', '>', ':', '"', '|', '?', '*' }) >= 0)
            {
                Debug.LogWarning($"输出目录包含非法字符: {validOutputDirectory}，使用默认目录: PrefabDocs");
                validOutputDirectory = "PrefabDocs";
            }
            
            // 如果是相对路径，确保它是基于项目路径的
            if (!Path.IsPathRooted(validOutputDirectory))
            {
                string projectPath = Application.dataPath.Substring(0, Application.dataPath.Length - 6);
                validOutputDirectory = Path.Combine(projectPath, validOutputDirectory);
                Debug.Log($"相对路径转换为绝对路径: {validOutputDirectory}");
            }
            
            // 更新有效的输出目录
            Debug.Log($"最终使用的输出目录: {validOutputDirectory}");
            outputDirectory = validOutputDirectory;
            SaveOutputDirectoryToPrefs();
            
            try 
            {
                if (!Directory.Exists(validOutputDirectory))
                {
                    Debug.Log($"创建输出目录: {validOutputDirectory}");
                    Directory.CreateDirectory(validOutputDirectory);
                }

                int successCount = 0;
                int totalFilesGenerated = 0;
                foreach (var prefabObj in selectedPrefabs)
                {
                    if (prefabObj == null) continue;
                    
                    string prefabPath = AssetDatabase.GetAssetPath(prefabObj);
                    if (string.IsNullOrEmpty(prefabPath))
                    {
                        Debug.LogWarning($"无法获取预制件路径: {prefabObj.name}");
                        continue;
                    }
                    
                    // 处理不同类型的预制件资源
                    GameObject gameObj = null;
                    if (prefabObj is GameObject)
                    {
                        gameObj = prefabObj as GameObject;
                    }
                    else 
                    {
                        gameObj = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
                    }
                    
                    if (gameObj != null)
                    {
                        string prefabName = Path.GetFileNameWithoutExtension(prefabPath);
                        string outputPath = Path.Combine(validOutputDirectory, prefabName + ".md");

                        int filesGenerated = 0;
                        if (GeneratePrefabDoc(gameObj, outputPath, out filesGenerated))
                        {
                            successCount++;
                            totalFilesGenerated += filesGenerated;
                        }
                    }
                    else
                    {
                        Debug.LogWarning($"无法加载为GameObject: {prefabPath}");
                    }
                }

                // 准备格式描述
                List<string> formatsList = new List<string>();
                if (useTreeFormat) formatsList.Add("树形格式");
                if (useCompactFormat) formatsList.Add("缩进格式");
                if (useCollapsibleFormat) formatsList.Add("MD折叠格式");
                string formatsDesc = string.Join("、", formatsList);

                string resultMsg = $"成功生成 {successCount}/{selectedPrefabs.Count} 个预制件的文档\n";
                resultMsg += $"生成的格式: {formatsDesc}\n";
                resultMsg += $"共生成 {totalFilesGenerated} 个文件\n\n";
                resultMsg += $"输出目录: {validOutputDirectory}";

                EditorUtility.DisplayDialog("完成", resultMsg, "确定");
            }
            catch (Exception ex)
            {
                Debug.LogError($"生成文档时出错: {ex.Message}");
                EditorUtility.DisplayDialog("错误", $"生成文档时出错: {ex.Message}", "确定");
            }
        }

        private void GenerateDocsForFolder(string folderPath)
        {
            if (!Directory.Exists(folderPath))
            {
                EditorUtility.DisplayDialog("错误", $"文件夹不存在: {folderPath}", "确定");
                return;
            }

            // 确保输出目录是有效路径
            string validOutputDirectory = outputDirectory;
            Debug.Log($"批量生成文档使用目录: {validOutputDirectory}");
            
            // 移除路径中可能存在的无效字符
            foreach (char invalidChar in Path.GetInvalidPathChars())
            {
                validOutputDirectory = validOutputDirectory.Replace(invalidChar.ToString(), "");
            }
            
            // 如果路径为空，使用默认值
            if (string.IsNullOrWhiteSpace(validOutputDirectory))
            {
                validOutputDirectory = "PrefabDocs";
                Debug.LogWarning("输出目录为空，使用默认目录: PrefabDocs");
            }
            
            // 确保路径不包含非法字符或格式
            // 对于Windows路径，允许第二个字符是冒号（例如C:）
            if (validOutputDirectory.Length >= 2 && validOutputDirectory[1] == ':')
            {
                // Windows路径，允许盘符后的冒号
                string pathWithoutDrive = validOutputDirectory.Substring(2);
                if (pathWithoutDrive.IndexOfAny(new char[] { '<', '>', ':', '"', '|', '?', '*' }) >= 0)
                {
                    Debug.LogWarning($"输出目录包含非法字符: {validOutputDirectory}，使用默认目录: PrefabDocs");
                    validOutputDirectory = "PrefabDocs";
                }
            }
            else if (validOutputDirectory.IndexOfAny(new char[] { '<', '>', ':', '"', '|', '?', '*' }) >= 0)
            {
                Debug.LogWarning($"输出目录包含非法字符: {validOutputDirectory}，使用默认目录: PrefabDocs");
                validOutputDirectory = "PrefabDocs";
            }
            
            // 如果是相对路径，确保它是基于项目路径的
            if (!Path.IsPathRooted(validOutputDirectory))
            {
                string projectPath = Application.dataPath.Substring(0, Application.dataPath.Length - 6);
                validOutputDirectory = Path.Combine(projectPath, validOutputDirectory);
                Debug.Log($"相对路径转换为绝对路径: {validOutputDirectory}");
            }
            
            // 更新有效的输出目录
            Debug.Log($"最终使用的输出目录: {validOutputDirectory}");
            outputDirectory = validOutputDirectory;
            SaveOutputDirectoryToPrefs();
            
            try
            {
                if (!Directory.Exists(validOutputDirectory))
                {
                    Debug.Log($"创建输出目录: {validOutputDirectory}");
                    Directory.CreateDirectory(validOutputDirectory);
                }

                string[] prefabPaths = Directory.GetFiles(folderPath, "*.prefab", SearchOption.AllDirectories);
                
                if (prefabPaths.Length == 0)
                {
                    EditorUtility.DisplayDialog("提示", $"在文件夹 {folderPath} 中未找到预制件文件", "确定");
                    return;
                }
                
                int successCount = 0;
                int totalFilesGenerated = 0;
                List<string> failedPrefabs = new List<string>();

                EditorUtility.DisplayProgressBar("生成预制件文档", "正在准备...", 0f);
                
                for (int i = 0; i < prefabPaths.Length; i++)
                {
                    string prefabPath = prefabPaths[i];
                    
                    // 更新进度条
                    float progress = (float)i / prefabPaths.Length;
                    EditorUtility.DisplayProgressBar("生成预制件文档", 
                                                   $"正在处理 {Path.GetFileName(prefabPath)} ({i+1}/{prefabPaths.Length})", 
                                                   progress);
                    
                    string relativePath = prefabPath.Replace('\\', '/');
                    if (!relativePath.StartsWith("Assets/"))
                    {
                        // 尝试转换为相对路径
                        if (relativePath.Contains(Application.dataPath))
                        {
                            relativePath = "Assets" + relativePath.Substring(Application.dataPath.Length);
                        }
                        else
                        {
                            relativePath = "Assets/" + relativePath;
                        }
                    }

                    GameObject prefabObj = AssetDatabase.LoadAssetAtPath<GameObject>(relativePath);
                    if (prefabObj != null)
                    {
                        string prefabName = Path.GetFileNameWithoutExtension(prefabPath);
                        string outputPath = Path.Combine(validOutputDirectory, prefabName + ".md");

                        int filesGenerated = 0;
                        if (GeneratePrefabDoc(prefabObj, outputPath, out filesGenerated))
                        {
                            successCount++;
                            totalFilesGenerated += filesGenerated;
                        }
                        else
                        {
                            failedPrefabs.Add(prefabName);
                        }
                    }
                    else
                    {
                        failedPrefabs.Add(Path.GetFileName(prefabPath));
                        Debug.LogWarning($"无法加载预制件: {relativePath}");
                    }
                }
                
                EditorUtility.ClearProgressBar();

                // 准备格式描述
                List<string> formatsList = new List<string>();
                if (useTreeFormat) formatsList.Add("树形格式");
                if (useCompactFormat) formatsList.Add("缩进格式");
                if (useCollapsibleFormat) formatsList.Add("MD折叠格式");
                string formatsDesc = string.Join("、", formatsList);

                string resultMessage = $"成功生成 {successCount}/{prefabPaths.Length} 个预制件的文档\n";
                resultMessage += $"生成的格式: {formatsDesc}\n";
                resultMessage += $"共生成 {totalFilesGenerated} 个文件\n\n";
                resultMessage += $"输出目录: {validOutputDirectory}";
                
                if (failedPrefabs.Count > 0)
                {
                    resultMessage += "\n\n处理失败的预制件:";
                    for (int i = 0; i < Math.Min(failedPrefabs.Count, 10); i++)
                    {
                        resultMessage += $"\n- {failedPrefabs[i]}";
                    }
                    
                    if (failedPrefabs.Count > 10)
                    {
                        resultMessage += $"\n... 以及其他 {failedPrefabs.Count - 10} 个";
                    }
                }
                
                EditorUtility.DisplayDialog("完成", resultMessage, "确定");
            }
            catch (Exception ex)
            {
                EditorUtility.ClearProgressBar();
                Debug.LogError($"生成文档时出错: {ex.Message}");
                EditorUtility.DisplayDialog("错误", $"生成文档时出错: {ex.Message}", "确定");
            }
        }

        private bool GeneratePrefabDoc(GameObject prefabObj, string outputPath, out int filesGenerated)
        {
            filesGenerated = 0;
            try
            {
                string prefabName = prefabObj.name;
                List<string> outputFiles = new List<string>();
                
                // 准备节点层级数据
                List<NodeInfo> nodes = new List<NodeInfo>();
                GetNodeHierarchy(prefabObj.transform, 0, nodes, "");
                var comments = nodeComments;
                
                // 为每种选中的格式生成文档
                if (useTreeFormat)
                {
                    StringBuilder content = new StringBuilder();
                    content.AppendLine($"# {prefabName} 节点层级结构 (树形格式)");
                    content.AppendLine();
                    content.AppendLine("```");
                    content.AppendLine(prefabName);

                    for (int i = 0; i < nodes.Count; i++)
                    {
                        if (nodes[i].level > 0) // 跳过根节点
                        {
                            string indent = new string(' ', nodes[i].level * 2);
                            string symbol = "├── ";

                            bool isLastChild = (i == nodes.Count - 1 || nodes[i + 1].level <= nodes[i].level);
                            if (isLastChild)
                            {
                                symbol = "└── ";
                            }

                            string nodeName = nodes[i].name;
                            string line = $"{indent}{symbol}{nodeName}";

                            // 如果启用注释并且存在注释，则添加注释
                            if (generateWithComments && comments.ContainsKey(nodeName))
                            {
                                line += $" ({comments[nodeName]})";
                            }

                            content.AppendLine(line);

                            // 添加连接线，如果下一个节点是当前节点的子节点
                            if (i < nodes.Count - 1 && nodes[i + 1].level > nodes[i].level)
                            {
                                content.AppendLine($"{indent}│");
                            }
                        }
                    }
                    content.AppendLine("```");
                    
                    // 保存树形格式文档
                    string treeFormatPath = Path.Combine(Path.GetDirectoryName(outputPath), 
                                                      $"{prefabName}_tree.md");
                    File.WriteAllText(treeFormatPath, content.ToString());
                    outputFiles.Add(treeFormatPath);
                    filesGenerated++;
                }
                
                if (useCompactFormat)
                {
                    StringBuilder content = new StringBuilder();
                    content.AppendLine($"# {prefabName} 节点层级结构 (缩进格式)");
                    content.AppendLine();
                    content.AppendLine("```");
                    content.AppendLine(prefabName);

                    for (int i = 0; i < nodes.Count; i++)
                    {
                        if (nodes[i].level > 0) // 跳过根节点
                        {
                            string indent = new string(' ', nodes[i].level * 4); // 使用4个空格缩进
                            string nodeName = nodes[i].name;
                            string line = $"{indent}{nodeName}";

                            // 如果启用注释并且存在注释，则添加注释
                            if (generateWithComments && comments.ContainsKey(nodeName))
                            {
                                line += $" ({comments[nodeName]})";
                            }

                            content.AppendLine(line);
                        }
                    }
                    content.AppendLine("```");
                    
                    // 保存缩进格式文档
                    string compactFormatPath = Path.Combine(Path.GetDirectoryName(outputPath), 
                                                       $"{prefabName}_compact.md");
                    File.WriteAllText(compactFormatPath, content.ToString());
                    outputFiles.Add(compactFormatPath);
                    filesGenerated++;
                }
                
                if (useCollapsibleFormat)
                {
                    StringBuilder content = new StringBuilder();
                    content.AppendLine($"# {prefabName} 节点层级结构");
                    content.AppendLine();
                    
                    // 添加根节点
                    content.AppendLine($"- **{prefabName}**");
                    
                    // 构建节点树，支持折叠
                    for (int i = 0; i < nodes.Count; i++)
                    {
                        // 跳过根节点，因为已经单独添加了
                        if (nodes[i].level == 0) continue;
                        
                        string indent = new string(' ', nodes[i].level * 2);
                        string nodeName = nodes[i].name;
                        string displayName = nodeName;
                        
                        // 如果启用注释并且存在注释，则添加注释
                        if (generateWithComments && comments.ContainsKey(nodeName))
                        {
                            displayName += $" ({comments[nodeName]})";
                        }
                        
                        string line = $"{indent}- **{displayName}**";
                        content.AppendLine(line);
                    }
                    
                    // 保存MD格式文档 - 使用预制件名作为文件名
                    File.WriteAllText(outputPath, content.ToString());
                    outputFiles.Add(outputPath);
                    filesGenerated++;
                }
                
                // 为特殊前缀的节点生成单独文档
                if (generateSpecialPrefixDocs)
                {
                    Dictionary<string, List<NodeInfo>> specialNodes = new Dictionary<string, List<NodeInfo>>();
                    
                    // 查找所有特殊前缀节点
                    foreach (var node in nodes)
                    {
                        foreach (var prefix in specialPrefixes)
                        {
                            if (node.name.StartsWith(prefix))
                            {
                                // 获取该节点及其子节点的子树
                                List<NodeInfo> subTree = new List<NodeInfo>();
                                
                                // 检查节点是否有层级限制
                                if (nodeLevelLimits.ContainsKey(node.name))
                                {
                                    // 使用限制的层级深度
                                    int maxLevel = nodeLevelLimits[node.name];
                                    FindSubTreeWithLevelLimit(nodes, node, subTree, maxLevel);
                                }
                                else
                                {
                                    // 无限制深度
                                    FindSubTree(nodes, node, subTree);
                                }
                                
                                // 存储子树信息以便后续生成文档
                                specialNodes[node.name] = subTree;
                                break;
                            }
                        }
                    }
                    
                    // 为每个特殊节点生成独立文档
                    foreach (var specialNode in specialNodes)
                    {
                        string nodeName = specialNode.Key;
                        List<NodeInfo> subTree = specialNode.Value;
                        
                        // 使用节点名称作为文件名
                        string specialNodePath = Path.Combine(Path.GetDirectoryName(outputPath), 
                                                           $"{nodeName}.md");
                        
                        // 只使用可折叠格式生成特殊节点文档
                        StringBuilder content = new StringBuilder();
                        content.AppendLine($"# {nodeName} 节点结构");
                        content.AppendLine();
                        
                        // 添加根节点
                        content.AppendLine($"- **{nodeName}**");
                        
                        // 构建节点树，支持折叠
                        for (int i = 1; i < subTree.Count; i++) // 从1开始，跳过特殊节点自身
                        {
                            // 计算相对于特殊节点的层级
                            int relativeLevel = subTree[i].level - subTree[0].level;
                            
                            string indent = new string(' ', relativeLevel * 2);
                            string nodeNameInTree = subTree[i].name;
                            string displayName = nodeNameInTree;
                            
                            // 如果启用注释并且存在注释，则添加注释
                            if (generateWithComments && comments.ContainsKey(nodeNameInTree))
                            {
                                displayName += $" ({comments[nodeNameInTree]})";
                            }
                            
                            string line = $"{indent}- **{displayName}**";
                            content.AppendLine(line);
                        }
                        
                        // 保存特殊节点的MD文档
                        File.WriteAllText(specialNodePath, content.ToString());
                        outputFiles.Add(specialNodePath);
                        filesGenerated++;
                    }
                }

                // 输出生成的文件信息
                foreach (string file in outputFiles)
                {
                    Debug.Log($"预制件文档已生成: {file}");
                }
                
                return outputFiles.Count > 0;
            }
            catch (Exception ex)
            {
                Debug.LogError($"生成预制件文档时出错: {ex.Message}");
                return false;
            }
        }
        
        // 查找节点及其所有子节点形成的子树，但限制最大层级深度
        private void FindSubTreeWithLevelLimit(List<NodeInfo> allNodes, NodeInfo rootNode, List<NodeInfo> result, int maxDepth)
        {
            // 添加根节点
            result.Add(rootNode);
            
            // 如果深度限制为0，只返回根节点
            if (maxDepth <= 0) return;
            
            // 节点的索引
            int rootIndex = allNodes.IndexOf(rootNode);
            if (rootIndex < 0) return;
            
            // 如果是最后一个节点，没有子节点
            if (rootIndex >= allNodes.Count - 1) return;
            
            // 根节点的层级
            int rootLevel = rootNode.level;
            
            // 查找所有子节点（与根节点紧邻且层级大于根节点的节点）
            for (int i = rootIndex + 1; i < allNodes.Count; i++)
            {
                // 如果遇到了与根节点相同或更低层级的节点，则已经不属于当前子树了
                if (allNodes[i].level <= rootLevel)
                    break;
                    
                // 检查深度是否超出限制
                int currentDepth = allNodes[i].level - rootLevel;
                if (currentDepth <= maxDepth)
                {
                    // 添加符合深度限制的子节点
                    result.Add(allNodes[i]);
                }
            }
        }
        
        // 查找节点及其所有子节点形成的子树
        private void FindSubTree(List<NodeInfo> allNodes, NodeInfo rootNode, List<NodeInfo> result)
        {
            // 添加根节点
            result.Add(rootNode);
            
            // 节点的索引
            int rootIndex = allNodes.IndexOf(rootNode);
            if (rootIndex < 0) return;
            
            // 如果是最后一个节点，没有子节点
            if (rootIndex >= allNodes.Count - 1) return;
            
            // 根节点的层级
            int rootLevel = rootNode.level;
            
            // 查找所有子节点（与根节点紧邻且层级大于根节点的节点）
            for (int i = rootIndex + 1; i < allNodes.Count; i++)
            {
                // 如果遇到了与根节点相同或更低层级的节点，则已经不属于当前子树了
                if (allNodes[i].level <= rootLevel)
                    break;
                    
                // 否则，这是当前子树的一部分
                result.Add(allNodes[i]);
            }
        }

        private void GetNodeHierarchy(Transform transform, int level, List<NodeInfo> result, string pathPrefix)
        {
            if (transform == null) return;
            
            string nodePath = string.IsNullOrEmpty(pathPrefix) ? transform.name : $"{pathPrefix}/{transform.name}";
            result.Add(new NodeInfo
            {
                name = transform.name,
                path = nodePath,
                level = level
            });

            // 递归处理所有子节点
            for (int i = 0; i < transform.childCount; i++)
            {
                Transform childTransform = transform.GetChild(i);
                GetNodeHierarchy(childTransform, level + 1, result, nodePath);
            }
        }

        private void ImportComments(string filePath)
        {
            try
            {
                string json = File.ReadAllText(filePath);
                PrefabDocGenerator tempInstance = CreateInstance<PrefabDocGenerator>();
                EditorJsonUtility.FromJsonOverwrite(json, tempInstance);
                
                // 从临时实例复制注释
                commentKeys = tempInstance.commentKeys;
                commentValues = tempInstance.commentValues;
                
                // 清理临时实例
                DestroyImmediate(tempInstance);
                
                SaveCommentsToPrefs();
                EditorUtility.DisplayDialog("成功", "注释已导入", "确定");
                Repaint();
            }
            catch (Exception ex)
            {
                EditorUtility.DisplayDialog("错误", $"导入注释失败: {ex.Message}", "确定");
            }
        }

        private void ExportComments(string filePath)
        {
            try
            {
                string json = EditorJsonUtility.ToJson(this, true);
                File.WriteAllText(filePath, json);
                EditorUtility.DisplayDialog("成功", "注释已导出到: " + filePath, "确定");
            }
            catch (Exception ex)
            {
                EditorUtility.DisplayDialog("错误", $"导出注释失败: {ex.Message}", "确定");
            }
        }

        private void ImportNodeLimits(string filePath)
        {
            try
            {
                string json = File.ReadAllText(filePath);
                NodeLimitsWrapper wrapper = JsonUtility.FromJson<NodeLimitsWrapper>(json);
                
                if (wrapper != null && wrapper.nodeLimitPairs != null)
                {
                    nodeLevelLimits = new Dictionary<string, int>();
                    foreach (var pair in wrapper.nodeLimitPairs)
                    {
                        if (!string.IsNullOrEmpty(pair.nodeName))
                        {
                            nodeLevelLimits[pair.nodeName] = pair.level;
                        }
                    }
                    
                    SaveNodeLimitsToPrefs();
                    EditorUtility.DisplayDialog("成功", "节点层级限制已导入", "确定");
                    Repaint();
                }
                else
                {
                    EditorUtility.DisplayDialog("错误", "导入的文件格式无效", "确定");
                }
            }
            catch (Exception ex)
            {
                EditorUtility.DisplayDialog("错误", $"导入节点层级限制失败: {ex.Message}", "确定");
            }
        }

        private void ExportNodeLimits(string filePath)
        {
            try
            {
                string json = JsonUtility.ToJson(new NodeLimitsWrapper(nodeLevelLimits), true);
                File.WriteAllText(filePath, json);
                EditorUtility.DisplayDialog("成功", "节点层级限制已导出到: " + filePath, "确定");
            }
            catch (Exception ex)
            {
                EditorUtility.DisplayDialog("错误", $"导出节点层级限制失败: {ex.Message}", "确定");
            }
        }

        [Serializable]
        private class NodeInfo
        {
            public string name;
            public string path;
            public int level;
        }
        
        [Serializable]
        private class NodeLimitPair
        {
            public string nodeName;
            public int level;
            
            public NodeLimitPair(string name, int lvl)
            {
                nodeName = name;
                level = lvl;
            }
        }
        
        [Serializable]
        private class NodeLimitsWrapper
        {
            public List<NodeLimitPair> nodeLimitPairs;
            
            public NodeLimitsWrapper(Dictionary<string, int> limits)
            {
                nodeLimitPairs = new List<NodeLimitPair>();
                if (limits != null)
                {
                    foreach (var kvp in limits)
                    {
                        nodeLimitPairs.Add(new NodeLimitPair(kvp.Key, kvp.Value));
                    }
                }
            }
            
            public NodeLimitsWrapper() 
            {
                nodeLimitPairs = new List<NodeLimitPair>();
            }
        }
    }
} 